package com.hs.ble;


import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.chiemy.cardview.util.DataHandlerUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Semaphore;


@SuppressLint("NewApi")
public class BluetoothLeService extends Service{
	
	public static Semaphore write_characer_lock = new Semaphore(1);
	private static int mPlayCount = 0;
	private int mRes = 0;
	private final static String TAG = BluetoothLeService.class.getSimpleName();

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGatt;

    private int mConnectionState = STATE_DISCONNECTED;
    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;
    
    public final static String ACTION_BLE_RECV_DATA =
            "com.example.bluetooth.le.ACTION_BLE_RECV_DATA";
    
    public final static String ACTION_THEMOMETER_RECV_VALUE =
            "com.example.bluetooth.le.ACTION_THEMOMETER_RECV_VALUE";
    
    
    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE =
            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";

    public final static String ACTION_GATT_CHARACTER_NOTIFY =
            "com.example.bluetooth.le.ACTION_GATT_CHARACTER_NOTIFY";
    
    public final static String EXTRA_DATA =
            "com.example.bluetooth.le.EXTRA_DATA";
    
    public final static String ARRAY_BYTE_DATA =
            "com.example.bluetooth.le.ARRAY_BYTE_DATA";

    public final static String ACTION_GATT_WRITE_RESULT =
            "com.example.bluetooth.le.ACTION_GATT_WRITE_RESULT";
    
    public final static String OTA_RX_DAT_ACTION = 
    		"com.hs.bluetooth.le.OTA_RX_DAT_ACTION";
    
    public final static String OTA_RX_CMD_ACTION = 
    		"com.hs.bluetooth.le.OTA_RX_CMD_ACTION";

    public final static String OTA_RX_ISP_CMD_ACTION =
            "com.hs.bluetooth.le.OTA_RX_ISP_CMD_ACTION";
    		
    public final static UUID UUID_HEART_RATE_MEASUREMENT =
            UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);

    public final static UUID UUID_RSSI_VALUE =
            UUID.fromString(SampleGattAttributes.RSSI_VALUE);
    
    public final static UUID UUID_RSSI_CONFIGARATION =
            UUID.fromString(SampleGattAttributes.RSSI_CONFIGARATION);
    
    public final static UUID UUID_BLUE_RECV_VALUE =
            UUID.fromString(SampleGattAttributes.BLUE_RECV_VALUE);
    
    public final static UUID UUID_TEMPERATURE_MEASUREMENT = 
    		UUID.fromString(SampleGattAttributes.TEMP_MEASUREMENT);
    
    public final static UUID UUID_OTA_TX_CMD = 
    		UUID.fromString(SampleGattAttributes.otas_tx_cmd_uuid);

    public final static UUID UUID_ISP_TX_CMD =
            UUID.fromString(SampleGattAttributes.otas_tx_ips_cmd_uuid);

    
    public final static UUID UUID_OTA_TX_DAT = 
    		UUID.fromString(SampleGattAttributes.otas_tx_dat_uuid);
    
    public final static UUID UUID_OTA_RX_CMD = 
    		UUID.fromString(SampleGattAttributes.otas_rx_cmd_uuid);

    public final static UUID UUID_ISP_RX_CMD =
            UUID.fromString(SampleGattAttributes.otas_rx_ips_cmd_uuid);

    public final static UUID UUID_OTA_RX_DAT = 
    		UUID.fromString(SampleGattAttributes.otas_rx_dat_uuid);
    
    private Context mContext;
    public static final String ACTION_SEND_DATA_TO_BLE = "com.chiemy.cardview.ACTION_SEND_DATA_TO_BLE";
    public static final String EXTRA_SEND_DATA_TO_BLE = "com.chiemy.cardview.EXTRA_SEND_DATA_TO_BLE";
    private static final int SEND_PACKET_SIZE = 20;
    private static final int FREE = 0;
    private static final int SENDING = 1;
    private static final int RECEIVING = 2;
    private int ble_status = FREE;
    private int packet_counter = 0;
    private int send_data_pointer = 0;
    private byte[] send_data = null;
    private boolean first_packet = false;
    private boolean final_packet = false;
    private boolean packet_send = false;
    private Timer mTimer;
    private int time_out_counter = 0;
    private int TIMER_INTERVAL = 100;
    private int TIME_OUT_LIMIT = 100;
    public ArrayList<byte[]> data_queue = new ArrayList<byte[]>();
    boolean sendingStoredData = false;
    private Timer timer;
    @Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return mBinder;
	}
	@Override
    public boolean onUnbind(Intent intent) {
        // After using a given device, you should make sure that BluetoothGatt.close() is called
        // such that resources are cleaned up properly.  In this particular example, close() is
        // invoked when the UI is disconnected from the Service.
     
        return super.onUnbind(intent);
    }

    private final IBinder mBinder = new LocalBinder();
    
    public class LocalBinder extends Binder {
    	public BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }
    
    
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        	String intentAction;
        	if (newState == BluetoothProfile.STATE_CONNECTED) {
            	intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
//                Log.e("peng","ble change :connect");

                Log.i(TAG, "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

//                Log.e("peng","ble change : disconnect");
                Log.i(TAG, "Disconnected from GATT server.");
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                broadcastUpdate(intentAction);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            //if (status == BluetoothGatt.GATT_SUCCESS && mOnServiceDiscoverListener!=null) {
        	String intentAction;
            if (status == BluetoothGatt.GATT_SUCCESS) {
                	//mOnServiceDiscoverListener.onServiceDiscover(gatt);
				intentAction = ACTION_GATT_SERVICES_DISCOVERED;
            	//ShowGattServices(getSupportedGattServices());
            	broadcastUpdate(intentAction);
            	Log.i(TAG, "onServicesDiscovered");
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        

        
        
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic,
                                         int status) {
            Log.d(TAG, "onCharacteristicRead: ");
        	broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }

        /**
         * Callback triggered as a result of a remote characteristic notification.
         *
         * @param gatt GATT client the characteristic is associated with
         * @param characteristic Characteristic that has been updated as a result
         *                       of a remote notification event.
         */
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            Log.d(TAG, "onCharacteristicChanged: "+characteristic.getUuid().toString());

            //通知来消息了
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);

        		
        	if(SampleGattAttributes.otas_rx_dat_uuid.equals(characteristic.getUuid().toString()))
        	{
        		broadcastUpdate(OTA_RX_DAT_ACTION, characteristic);
        	}

            if(SampleGattAttributes.otas_rx_ips_cmd_uuid.equals(characteristic.getUuid().toString()))
            {
                broadcastUpdate(OTA_RX_ISP_CMD_ACTION, characteristic);
            }

            if(SampleGattAttributes.otas_rx_cmd_uuid.equals(characteristic.getUuid().toString()))
        	{
        		broadcastUpdate(OTA_RX_CMD_ACTION, characteristic);
        	}
        }
          
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){
        	
        	Log.i("DEBUG_OTA", "write status: "+status);
        	write_characer_lock.release(1);

        }
    };
    
    public boolean initialize() {
        // For API level 18 and above, get a reference to BluetoothAdapter through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }

        return true;
    }
    
    /**
     * Connects to the GATT server hosted on the Bluetooth LE device.
     *
     * @param address The device address of the destination device.
     *
     * @return Return true if the connection is initiated successfully. The connection result
     *         is reported asynchronously through the
     *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     *         callback.
     */
    public boolean connect(final String address) {
        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        // Previously connected device.  Try to reconnect.
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                && mBluetoothGatt != null) {
            Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                return true;
            } else {
                return false;
            }
        }

        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        // We want to directly connect to the device, so we are setting the autoConnect
        // parameter to false.
//        if (mContext == null) {
//            //vivo X7 plus  mContext == null
//            Log.e(TAG,"mContext == null");
//            return false;
//        }

        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        Log.d(TAG, "Trying to create a new connection.");
        mBluetoothDeviceAddress = address;
        return true;
    }

    /**
     * Disconnects an existing connection or cancel a pending connection. The disconnection result
     * is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();
    }

    /**
     * After using a given BLE device, the app must call this method to ensure resources are
     * released properly.
     */
    public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    /**
     * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
     * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
     * callback.
     *
     * @param characteristic The characteristic to read from.
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled If true, enable notification.  False otherwise.
     */
    public boolean  setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return false;
        }
        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        UUID uuid = UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(uuid);

        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        return mBluetoothGatt.writeDescriptor(descriptor);
        
        
    }


    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_SEND_DATA_TO_BLE);
        LocalBroadcastManager.getInstance(this).registerReceiver(mServiceReceiver, intentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mServiceReceiver);
    }
    private final BroadcastReceiver mServiceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_SEND_DATA_TO_BLE)) {//from commandManager
                Log.i(TAG,"收到广播--发送数据到蓝牙设备");
                byte[] send_data = intent.getByteArrayExtra(EXTRA_SEND_DATA_TO_BLE);
                if (send_data != null) {
                    BLE_send_data_set(send_data, false);
                }
            }
        }
    };

    /**
     * 设置数据到内部缓冲区对BLE发送数据
     */
    private void BLE_send_data_set(byte[] data, boolean retry_status) {
        if (ble_status != FREE || mConnectionState != STATE_CONNECTED) {
            //蓝牙没有连接或是正在接受或发送数据，此时将要发送的指令加入集合
            if (sendingStoredData) {
                if (!retry_status) {
                    data_queue.add(data);
                }
                return;
            } else {
                data_queue.add(data);
                start_timer();
            }

        } else {
            ble_status = SENDING;

            if (data_queue.size() != 0) {
                send_data = data_queue.get(0);
                sendingStoredData = false;
            } else {
                send_data = data;
            }
            packet_counter = 0;
            send_data_pointer = 0;
            //第一个包
            first_packet = true;
            BLE_data_send();

            if (data_queue.size() != 0) {
                data_queue.remove(0);
            }

            if (data_queue.size() == 0) {
                if (mTimer != null) {
                    mTimer.cancel();
                }
            }
        }
    }
    /**
     * @brief Send data using BLE. 发送数据到蓝牙
     */
    private void BLE_data_send() {
        int err_count = 0;
        int send_data_pointer_save;
        int wait_counter;
        boolean first_packet_save;
        while (!final_packet) {
            //不是最后一个包
            byte[] temp_buffer;
            send_data_pointer_save = send_data_pointer;
            first_packet_save = first_packet;
            if (first_packet) {
                //第一个包

                if ((send_data.length - send_data_pointer) > (SEND_PACKET_SIZE)) {
                    temp_buffer = new byte[SEND_PACKET_SIZE];//20
                    for (int i = 0; i < SEND_PACKET_SIZE; i++) {
                        //将原数组加入新创建的数组
                        temp_buffer[i] = send_data[send_data_pointer];
                        send_data_pointer++;
                    }
                } else {
                    //发送的数据包不大于20
                    temp_buffer = new byte[send_data.length - send_data_pointer];
                    for (int i = 0; i < temp_buffer.length; i++) {
                        //将原数组未发送的部分加入新创建的数组
                        temp_buffer[i] = send_data[send_data_pointer];
                        send_data_pointer++;
                    }
                    final_packet = true;
                }
                first_packet = false;
            } else {
                //不是第一个包
                if (send_data.length - send_data_pointer >= SEND_PACKET_SIZE) {
                    temp_buffer = new byte[SEND_PACKET_SIZE];
                    temp_buffer[0] = (byte) packet_counter;
                    for (int i = 1; i < SEND_PACKET_SIZE; i++) {
                        temp_buffer[i] = send_data[send_data_pointer];
                        send_data_pointer++;
                    }
                } else {
                    final_packet = true;
                    temp_buffer = new byte[send_data.length - send_data_pointer + 1];
                    temp_buffer[0] = (byte) packet_counter;
                    for (int i = 1; i < temp_buffer.length; i++) {
                        temp_buffer[i] = send_data[send_data_pointer];
                        send_data_pointer++;
                    }
                }
                packet_counter++;
            }
            packet_send = false;

            boolean status = writeRXCharacteristic(temp_buffer);
            if ((status == false) && (err_count < 3)) {
                err_count++;
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                send_data_pointer = send_data_pointer_save;
                first_packet = first_packet_save;
                packet_counter--;
            }
            // Send Wait
            for (wait_counter = 0; wait_counter < 5; wait_counter++) {
                if (packet_send == true) {
                    break;
                }
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        final_packet = false;
        ble_status = FREE;
    }
    /**
     * 定时器
     */
    private void start_timer() {
        sendingStoredData = true;
        if (mTimer != null) {
            mTimer.cancel();
        }
        mTimer = new Timer(true);
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                timer_Tick();
            }
        }, 100, TIMER_INTERVAL);
    }

    /**
     * @brief Interval timer function.
     */
    private void timer_Tick() {

        if (data_queue.size() != 0) {
            sendingStoredData = true;
            BLE_send_data_set(data_queue.get(0), true);
        }

        if (time_out_counter < TIME_OUT_LIMIT) {
            time_out_counter++;
        } else {
            ble_status = FREE;
            time_out_counter = 0;
        }
        return;
    }
    /**
     * 向蓝牙设备写入字节数据
     * @param value
     */
    public boolean writeRXCharacteristic(byte[] value)
    {
        if (mBluetoothGatt==null) {
            return false;
        }

        BluetoothGattService RxService = mBluetoothGatt.getService(SampleGattAttributes.WAKE_RX_SERVICE_UUID);
        if (RxService == null) {
            Log.e(TAG,"Rx service not found!");
            return false;
        }
        BluetoothGattCharacteristic RxChar = RxService.getCharacteristic(SampleGattAttributes.WAKE_RX_CHAR_UUID);
        if (RxChar == null) {
            Log.e(TAG,"Rx charateristic not found!");
            return false;
        }
        RxChar.setValue(value);
        boolean status = mBluetoothGatt.writeCharacteristic(RxChar);

        Log.d(TAG, "write TXchar - status=" + status+ DataHandlerUtils.bytesToHexStr(value));
        return status;

    }
    public boolean  writeCharacteristic(BluetoothGattCharacteristic characteristic){
		try {
			write_characer_lock.acquire(1);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(mBluetoothGatt == null) {
            return false;
        }
    	 return mBluetoothGatt.writeCharacteristic(characteristic);
    }
    /**
     * Retrieves a list of supported GATT services on the connected device. This should be
     * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
     *
     * @return A {@code List} of supported services.
     */
    public List<BluetoothGattService> getSupportedGattServices() {
        if (mBluetoothGatt == null) {
            return null;
        }

        return mBluetoothGatt.getServices();
    }
    
    
    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        Log.i(TAG, "in " + action);
        sendBroadcast(intent);
    }

    /**
     * 发送广播
     * @param action
     * @param characteristic
     */
    private void broadcastUpdate(final String action,
            final BluetoothGattCharacteristic characteristic) {
        Log.i(TAG,"uuid: "+characteristic.getUuid().toString());

	final Intent intent = new Intent(action);

	if(UUID_OTA_RX_DAT.equals(characteristic.getUuid())){
	    Log.i(TAG,"UUID_OTA_RX_DAT");
		final byte[] ota_rx_dat = characteristic.getValue();
		if (ota_rx_dat != null && ota_rx_dat.length > 0) {
			intent.putExtra(ARRAY_BYTE_DATA, ota_rx_dat);
		}
	}else if(UUID_OTA_RX_CMD.equals(characteristic.getUuid())){
        Log.i(TAG,"UUID_OTA_RX_CMD");
        final byte[] ota_rx_cmd = characteristic.getValue();
		if (ota_rx_cmd != null && ota_rx_cmd.length > 0) {
			intent.putExtra(ARRAY_BYTE_DATA, ota_rx_cmd);
		}
	}else if (UUID_ISP_RX_CMD.equals(characteristic.getUuid())){
        Log.i(TAG,"UUID_ISP_RX_CMD");

        byte[] value = characteristic.getValue();
        if (value != null && value.length>0){
            intent.putExtra(ARRAY_BYTE_DATA, value);
        }
    }
	else if (SampleGattAttributes.WAKE_TX_CHAR_UUID.equals(characteristic.getUuid())){
        Log.i(TAG,"WAKE_TX_CHAR_UUID");
        Log.d(TAG, "received from ble:" + DataHandlerUtils.bytesToHexStr(characteristic.getValue()));
        intent.putExtra(EXTRA_DATA, characteristic.getValue());

    }else {
	// For all other profiles, writes the data formatted in HEX.
		final byte[] data = characteristic.getValue();
		if (data != null && data.length > 0) {
			final StringBuilder stringBuilder = new StringBuilder(data.length);
			for(byte byteChar : data)
				stringBuilder.append(String.format("%02X ", byteChar));
			intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
		}
	}
		sendBroadcast(intent);
	}
    
   
    
}
